<template>
  <div class="container p-6">
    <!-- 搜索区域 -->
    <div class="mb-4 flex items-center space-x-4">
      <el-input
        v-model="searchParams.content"
        placeholder="输入试题名称"
        class="!w-[200px]"
        clearable
        @input="handleAutoSearch"
        @clear="handleAutoSearch"
        size="large"
      />
      <el-select
        v-model="searchParams.repoId"
        placeholder="选择或搜索题库"
        class="!w-[200px]"
        filterable
        clearable
        @change="handleAutoSearch"
        size="large"
      >
        <el-option
          v-for="item in repoList"
          :key="item.id"
          :label="item.title"
          :value="item.id"
        />
      </el-select>
      <el-select
        v-model="searchParams.type"
        placeholder="请选择"
        class="!w-[200px]"
        clearable
        @change="handleAutoSearch"
        size="large"
      >
        <el-option
          v-for="item in questionTypeList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" @click="handleAdd" size="large">新增</el-button>
      <el-button type="primary" @click="handleImport" size="large"
        >导入</el-button
      >
      <el-button
        type="danger"
        @click="handleBatchDelete"
        :disabled="selectedRows.length === 0"
        size="large"
        >批量删除</el-button
      >
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="id" label="序号" width="80" align="center" />
      <el-table-column
        prop="content"
        label="题干"
        max-width="250"
        align="center"
      />
      <el-table-column
        prop="quType"
        label="题目类型"
        width="120"
        align="center"
      >
        <template #default="scope">
          {{ getQuestionType(scope.row.quType) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="repoTitle"
        label="所属题库"
        width="150"
        align="center"
      />
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180"
        align="center"
      />
      <el-table-column label="操作" width="150" align="center" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="mt-4 flex items-center text-sm text-gray-500">
      <span>共 {{ searchParams.total }} 条</span>
      <div class="ml-4 flex items-center">
        <el-select
          v-model="searchParams.pageSize"
          class="!w-[100px] mr-2"
          @change="handleSizeChange"
        >
          <el-option
            v-for="size in [10, 20, 30, 50]"
            :key="size"
            :label="`${size}条/页`"
            :value="size"
          />
        </el-select>
        <el-pagination
          v-model:current-page="searchParams.pageNum"
          :page-size="searchParams.pageSize"
          layout="prev, pager, next"
          :total="searchParams.total"
          :pager-count="5"
          background
          @current-change="handleCurrentChange"
        />
        <span class="mx-2">前往</span>
        <el-input
          v-model="jumpPage"
          class="!w-[50px]"
          @keyup.enter="handleJumpPage"
        />
        <span class="mx-2">页</span>
      </div>
    </div>

    <!-- 导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入试题"
      width="400px"
      :close-on-click-modal="false"
      :before-close="closeImportDialog"
    >
      <el-form>
        <el-form-item label="选择题库">
          <el-select
            v-model="importRepoId"
            placeholder="请选择题库"
            style="width: 100%"
            size="large"
          >
            <el-option
              v-for="item in repoList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="上传文件">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :limit="1"
            :file-list="fileList"
            accept=".xlsx,.xls"
            :show-file-list="true"
          >
            <div class="flex flex-col items-center justify-center py-8">
              <el-icon class="el-icon--upload text-5xl text-gray-300 mb-4">
                <upload-filled />
              </el-icon>
              <div class="el-upload__text text-base mb-2">
                将文件拖到此处，或<em class="text-blue-500 font-medium"
                  >点击上传</em
                >
              </div>
              <div class="el-upload__tip text-xs text-gray-500">
                只能上传xlsx或xls文件，且不超过1500kb
              </div>
            </div>
            <template #tip>
              <div class="mt-2 text-sm text-gray-500">
                <el-button
                  type="primary"
                  link
                  @click="downloadTemplate"
                  size="large"
                  >下载模板</el-button
                >
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <!-- 显示上传进度 -->
        <el-form-item v-if="uploadProgress > 0 && uploadProgress < 100">
          <el-progress
            :percentage="uploadProgress"
            :format="percentageFormat"
            :status="uploadProgress < 100 ? '' : 'success'"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeImportDialog" size="large">取消</el-button>
          <el-button
            type="primary"
            @click="submitImport"
            :loading="uploadLoading"
            size="large"
            >导入</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getTestQuestionsList,
  importQuestions,
} from '@/api/teacher/testquestions'
import { getRepolist } from '@/api/teacher/question'
import { uploadImage } from '@/api/teacher/index'
import { useRouter } from 'vue-router'
import { UploadFilled } from '@element-plus/icons-vue'

const router = useRouter()

// 表格数据
const tableData = ref([])
const loading = ref(false)
const repoList = ref([])

// 题目类型
const questionTypeList = ref([
  { value: 0, label: '全部类型' },
  { value: 1, label: '单选题' },
  { value: 2, label: '多选题' },
  { value: 3, label: '判断题' },
  { value: 4, label: '简答题' },
])

// 分页相关
const searchParams = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  content: '',
  repoId: '',
  type: 0,
})

// 跳转页码
const jumpPage = ref('')

// 选中的行
const selectedRows = ref([])

// 导入相关变量
const importDialogVisible = ref(false)
const importRepoId = ref('')
const importFile = ref(null)
const fileList = ref([])
const uploadProgress = ref(0)
const uploadLoading = ref(false)

// 获取题库列表
const getRepoList = async () => {
  try {
    const { data } = await getRepolist()
    repoList.value = data
  } catch (error) {
    ElMessage.error('获取题库列表失败')
  } finally {
    loading.value = false
  }
}

// 获取题目列表
const getQuestionList = async () => {
  if (loading.value) return
  loading.value = true
  try {
    const { data } = await getTestQuestionsList(searchParams)
    tableData.value = data.records
    searchParams.total = data.total
    searchParams.pageNum = data.current
  } catch (error) {
    console.error('获取题目列表失败:', error)
    ElMessage.error('获取题目列表失败')
  } finally {
    loading.value = false
  }
}

// 获取题目类型文本
const getQuestionType = (type) => {
  return (
    questionTypeList.value.find((item) => item.value === type)?.label ||
    '未知类型'
  )
}

// 处理搜索
const handleSearch = () => {
  searchParams.pageNum = 1
  getQuestionList()
}

// 自动搜索（防抖）
let searchTimer = null
const handleAutoSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  searchTimer = setTimeout(() => {
    handleSearch()
  }, 500)
}

// 处理新增
const handleAdd = () => {
  // TODO: 实现新增逻辑
  router.push('/teacher/addquestion')
}

// 处理导入
const handleImport = () => {
  importDialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  router.push(`/teacher/addquestion?id=${row.id}`)
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该题目吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      // TODO: 实现删除逻辑
      ElMessage.success('删除成功')
      getQuestionList()
    })
    .catch(() => {
      // 取消删除
    })
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  searchParams.pageSize = val
  getQuestionList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  searchParams.pageNum = val
  getQuestionList()
}

// 处理跳转页码
const handleJumpPage = () => {
  const page = Number(jumpPage.value)
  if (
    page &&
    page > 0 &&
    page <= Math.ceil(searchParams.total / searchParams.pageSize)
  ) {
    searchParams.pageNum = page
    getQuestionList()
  } else {
    ElMessage.warning('请输入有效的页码')
  }
  jumpPage.value = ''
}

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedRows.value = val
}

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 个题目吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        // 获取所有选中行的ID
        const ids = selectedRows.value.map((row) => row.id)
        // TODO: 调用批量删除API
        ElMessage.success('批量删除成功')
        // 刷新表格数据
        getQuestionList()
        // 清空选中
        selectedRows.value = []
      } catch (error) {
        console.error('批量删除出错：', error)
        ElMessage.error('批量删除失败，请稍后重试')
      }
    })
    .catch(() => {
      // 取消删除
    })
}

// 处理文件上传
const handleFileChange = (file) => {
  const allowedTypes = [
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  ]

  if (allowedTypes.indexOf(file.raw.type) === -1) {
    ElMessage.error('只能上传Excel文件！')
    fileList.value = []
    return false
  }

  if (file.size / 1024 > 1500) {
    ElMessage.error('文件大小不能超过1500KB!')
    fileList.value = []
    return false
  }

  fileList.value = [file]
  importFile.value = file.raw
  return false
}

// 处理文件删除
const handleFileRemove = () => {
  fileList.value = []
  importFile.value = null
  uploadProgress.value = 0
}

// 下载模板
const downloadTemplate = () => {
  const link = document.createElement('a')
  link.href = '/template/试题导入模板.xlsx'
  link.download = '试题导入模板.xlsx'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 执行导入操作
const submitImport = () => {
  if (!importRepoId.value) {
    ElMessage.warning('请选择题库')
    return
  }

  if (!importFile.value) {
    ElMessage.warning('请选择文件')
    return
  }

  uploadLoading.value = true
  uploadProgress.value = 0

  const formData = new FormData()
  formData.append('file', importFile.value)

  // 创建一个上传进度计时器模拟进度
  let timer = setInterval(() => {
    if (uploadProgress.value < 90) {
      uploadProgress.value += 10
    } else {
      clearInterval(timer)
    }
  }, 300)

  importQuestions(importRepoId.value, formData)
    .then((res) => {
      clearInterval(timer)
      uploadProgress.value = 100

      setTimeout(() => {
        uploadLoading.value = false
        ElMessage.success('导入成功')
        closeImportDialog()
        loadData() // 重新加载数据
      }, 500)
    })
    .catch((err) => {
      clearInterval(timer)
      uploadProgress.value = 0
      uploadLoading.value = false
      ElMessage.error(err.message || '导入失败')
    })
}

// 重置导入表单
const resetImportForm = () => {
  importRepoId.value = ''
  importFile.value = null
  fileList.value = []
  uploadProgress.value = 0
}

// 关闭导入对话框
const closeImportDialog = () => {
  resetImportForm()
  importDialogVisible.value = false
}

// 页面加载时获取数据
onMounted(() => {
  getRepoList()
  getQuestionList()
})

function percentageFormat(percentage) {
  return percentage === 100 ? '上传完成' : `${percentage}%`
}

function loadData() {
  getQuestionList()
}
</script>

<style lang="less" scoped>
.container {
  background-color: white;
  border-radius: 8px;
  min-height: calc(100vh - 120px);
}

:deep(.el-table) {
  .cell {
    display: flex;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
  }

  .el-table__header th {
    .cell {
      justify-content: center;
    }
  }

  .el-button {
    margin: 0 auto;
  }
}

:deep(.el-pagination) {
  .el-pagination__total {
    margin-right: 16px;
  }

  .el-pagination__sizes {
    margin-right: 16px;
  }

  .el-pager li {
    background-color: transparent;

    &.is-active {
      background-color: var(--el-color-primary);
      color: white;
    }
  }

  .btn-prev,
  .btn-next {
    background-color: transparent;
  }

  .el-input__inner {
    text-align: center;
    padding: 0 5px;
  }
}

:deep(.el-select) {
  .el-input__wrapper {
    background-color: transparent;
  }
}

// 上传组件样式
:deep(.upload-demo) {
  .el-upload-dragger {
    width: 100%;
    height: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 2px dashed #d9d9d9;
    border-radius: 8px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;
    background-color: #f9f9f9;

    &:hover {
      border-color: #409eff;
      background-color: #f0f7ff;
    }
  }

  .el-icon--upload {
    font-size: 48px;
    color: #909399;
    margin-bottom: 16px;
    transition: transform 0.3s;
  }

  &:hover .el-icon--upload {
    transform: translateY(-5px);
    color: #409eff;
  }

  .el-upload__text {
    color: #606266;
    font-size: 16px;
    margin-bottom: 8px;

    em {
      color: #409eff;
      font-style: normal;
      font-weight: 500;
      text-decoration: underline;
    }
  }

  .el-upload__tip {
    color: #909399;
    font-size: 14px;
  }
}

// 导入对话框样式
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
